require'infopunk'
require'character'
AC_Events = class('AC_Events')

function AC_Events:initialize()
	print("Initializing AC_Events")

	self.infopunk = Infopunk:new(self)

	if INFOPUNK_DEBUG then
		self.infopunk:set_player(Character:new("Sho-Zan"))
	end

	self.time = {}
	self.time.start = os.time()
	self.time.now = self.time.start
	self.time.on = true
	self.time.login = false
	self.time.round_limit = 0.1
	self.time.round_counter = 0
	self:connectMainEvents()
	
	print("ac_events initialized")

end

function AC_Events:OnLogon(player)		
		
		self.infopunk.skapi:OutputLine("LUACOM: Connected to" .. player.szName, 
			self.infopunk.skapi.opmChatWnd, self.infopunk.skapi.cmcPaleRose)
		print(player.szName .. " connected")

		if not INFOPUNK_DEBUG then
			self.infopunk:set_player(Character:new(player.szName))
		end

	end

	function AC_Events:OnEnd3D()
		print(self.infpunk.skapi.szName .. " disconnecting")
		self.infopunk:exit(0)
	end

	function AC_Events:OnTellFellowship(sender, msg)

		self.infopunk:receive_command(sender, msg)
	end

	function AC_Events:OnActionComplete()
		local arc = self.infopunk.skapi.arc
		print("action complete code: " .. arc)
		if self.infopunk.buffself.buffing then
			print("in bufflist callback")
			

			
			if arc == 0  or arc == 1309 then
				print("action succeeded")
				table.remove(self.infopunk.buffself.buff_queue, 1)				
			else
				print("action failed")
			end
			self.infopunk:check_casting_vitals()
			self.infopunk.buffself.buff_finished = true
			
		end
	end

function AC_Events:start()
	self:mainLoop()
end



function AC_Events:connectMainEvents()
	-- receive events from skev, sent to ac_events
	local skev = self.infopunk.skapi.skev
	res, self.skev_cookie = luacom.Connect(skev, self)
	if not res then
		self.infopunk:exit(1)
	end
end

function AC_Events:disconnectMainEvents()
	luacom.releaseConnection(self.infopunk.skapi.skev, self, self.skev_cookie)
end

function AC_Events:mainLoop()
	while self.time.on do
		self.time.last = self.time.now 
		self.time.now = os.time()
		self.time.dt = self.time.now - self.time.last
		
		if self.time.now > self.time.last then
			self:Update(self.time.dt)
		end

	end


end

function AC_Events:Update()
	self.time.round_counter = self.time.round_counter+self.time.dt
	if self.time.round_counter > self.time.round_limit then		
		self.infopunk.skapi:WaitEvent(0)
		self.infopunk.buffself:update(self.time.dt)
	end
end


